#include "Sqlite3Database.h"

#define GLOG_USE_GLOG_EXPORT
#include <glog/logging.h>
#include <sqlite3.h>

Sqlite3Database::Sqlite3Database()
{
    m_database = nullptr;
}

Sqlite3Database::~Sqlite3Database()
{
}

bool Sqlite3Database::sqlite3Open(const std::string &filename)
{
    int ret = sqlite3_open(filename.c_str(), &m_database);
    if (ret != SQLITE_OK) {
        LOG(ERROR) << "Can't open database: " << sqlite3_errmsg(m_database);
        return false;
    }
    return true;
}

bool Sqlite3Database::sqlite3Close()
{
    int ret = sqlite3_close(m_database);
    if (ret != SQLITE_OK) {
        return false;
    }
    m_database = nullptr;
    return true;
}

bool Sqlite3Database::sqlite3Exec(const std::string &sql)
{
    return sqlite3Exec(
        sql,
        [](void *, int, char **, char **) -> int {
            return 0;
        },
        nullptr);
}

bool Sqlite3Database::sqlite3Exec(const std::string &sql, int (*callback)(void *, int, char **, char **), void *data)
{
    char *errmsg = 0;
    int   ret    = sqlite3_exec(m_database, sql.c_str(), callback, data, &errmsg);
    if (ret != SQLITE_OK) {
        LOG(ERROR) << "SQL execute error: " << errmsg;
        sqlite3_free(errmsg);
        return false;
    }
    return true;
}